import cheerioModule from "cheerio";
import { getLogger, Logger } from "log4js";
import { Collection } from "mongodb";
import { getAxios, sleep } from "../utils";
import { qiniu } from "../utils/qiniuLoad";
import dayjs from 'dayjs'
const INDEXURL = 'https://www.op.gg/champion/statistics'

const logger = getLogger('opgg')


export interface OPGG {
    _id?: string
    name_en: string
    name_zh: string
    position: string
    winner: string
    pick: string
    img: string
    tier: number
    updateTime: Date
    updateTimeStr: string
}

export async function opggIndex(hero: Map<string, string>, col: Collection<OPGG>, qiniuClient: qiniu, hero_alis: Map<string, string>) {
    const data = await getAxios(INDEXURL);

    console.log("start")
    if (data === '404') {
        logger.error(`opgg index axios is 404`)
        return
    }
    const $ = cheerioModule.load(data)
    const arrs = ['top', 'jug', 'mid', 'adc', 'sup']
    const first = $('.detail-ranking__wrapper--content').eq(0)
    const lists = $('.detail-ranking__content--champ-list', first)
    for (const list of lists) {
        const lss = $('ul', list).children()
        for (const item of lss) {
            const name = $('.champion-ratio__name', item).text().replace(/\s/g, '')
            const win = $('.champion-ratio__percent div', item).eq(0).text()
            const pick = $('.champion-ratio__percent div', item).eq(1).text()
            const tier = $('.champion-ratio__tier img', item).attr('src')
            let img: string = hero_alis.get(name) || ""
            if (img.length === 0) {
                img = `https://game.gtimg.cn/images/lol/act/img/champion/${name}.png`
            }
            if (!tier) continue
            const date = new Date();
            const res: OPGG = {
                _id: `${arrs[0]}_${name}`,
                name_en: name.replace(/\s/g, ''),
                name_zh: hero.get(name) || "",
                position: arrs[0],
                winner: win,
                pick: pick,
                img: img,
                tier: Number(tier.replace('//opgg-static.akamaized.net/images/site/champion/icon-champtier-', '').split('.')[0]),
                updateTime: date,
                updateTimeStr: dayjs(date).add(8,'h').format("YYYY-MM-DD HH:mm:ss")
            }
            console.log(JSON.stringify(res))
            try {
                await col.updateOne({ _id: res._id }, { $set: res }, { upsert: true })
            } catch (error: any) {
                logger.error(`updateone is error ${error.message}`)
            }
        }
        arrs.shift()
    }

}